from mcp.server.fastmcp import FastMCP
import json
from typing import TypedDict
from pydantic import BaseModel, Field

mcp = FastMCP(name="MCP Server")


# 1.定义pydantic BaseModel用来返回结构化的天气数据
class WeatherData(BaseModel):
    temperature: float = Field(description="温度")
    humidity: float = Field(description="湿度")
    condition: str = Field(description="天气状况")


@mcp.tool()
def get_weather(city: str) -> WeatherData:
    return WeatherData(temperature=22.5, humidity=60, condition=f"sunny in {city}")


# 2、定义TypedDict用于返回结构化地理信息
class LocationInfo(TypedDict):
    latitude: float
    longitude: float
    name: str


@mcp.tool()
def get_location(address: str) -> LocationInfo:
    return LocationInfo(latitude=22.5, longitude=60, name=f"{address}")


# 3、返回dict[str, float]等可推导Schema的类型
@mcp.tool()
def get_statistics() -> dict[str, float]:
    return {"mean": 77, "median": 98}


# 4、定义带类型注解的普通类（有类型提示的属性可被推断）
class UserProfile:
    name: str
    age: int
    email: str | None

    def __init__(self, name: str, age: int, email: str | None = None) -> None:
        self.name = name
        self.age = age
        self.email = email


@mcp.tool()
def get_user() -> UserProfile:
    return UserProfile(name="Alice", age=18, email=None)


# 5、返回原始类型与列表类型：将被自动包装为{"result": ...}
# 注册为工具：返回温度（原始浮点数）
@mcp.tool()
def get_temperature() -> float:
    # 返回温度（原始浮点数，客户端会在structuredContent.result中看到）
    return 21.7


# 6
@mcp.tool()
def list_cities() -> list[str]:
    # 返回城市列表（列表会被包装到structuredContent.result中看到）
    return ["南京", "常州", "镇江"]


# 7、定义不可序列化的类（无类型注解字段）：将被视为非结构化
class UntypedConfig:
    def __init__(self, setting1, setting2):
        self.setting1 = setting1
        self.setting2 = setting2


@mcp.tool()
def get_config() -> UntypedConfig:
    # 返回非结构化的配置对象 将作为文本内容返回
    return UntypedConfig("value1", "value2")


# 8、禁用结构化输出，即使返回的是dict,也按非结构处理
@mcp.tool(structured_output=False)
def unstructured_message() -> dict[str, str]:
    return {"msg": "这将返回一个非结构化内容"}


if __name__ == "__main__":
    mcp.run(transport="stdio")
